package com.h3bpm.starcharge.common.uitl.k3c;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * K/3 Cloud Web API集成
 *
 * @author LLongAgo
 * @date 2019/2/28
 * @since 1.0.0
 */
public class InvokeHelper {

    public static String POST_K3CloudURL = "http://10.9.35.27/k3cloud/";

    // Cookie 值
    private static String CookieVal = null;

    private static Map<String, String> map = new HashMap<>();
    static {
        map.put("Save",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc");
        map.put("View",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc");
        map.put("Submit",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit.common.kdsvc");
        map.put("Audit",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Audit.common.kdsvc");
        map.put("UnAudit",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.UnAudit.common.kdsvc");
        map.put("StatusConvert",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.StatusConvert.common.kdsvc");
        map.put("Draft",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Draft.common.kdsvc");
        map.put("BatchSave",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.BatchSave.common.kdsvc");
        map.put("Allocate",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Allocate.common.kdsvc");
        map.put("ExecuteBillQuery",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc");
        map.put("Push",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Push.common.kdsvc");
        map.put("Delete",
                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Delete.common.kdsvc");

    }

    // HttpURLConnection
    private static HttpURLConnection initUrlConn(String url, JSONArray paras)
            throws Exception {
        URL postUrl = new URL(POST_K3CloudURL.concat(url));
        HttpURLConnection connection = (HttpURLConnection) postUrl
                .openConnection();
        if (CookieVal != null) {
            connection.setRequestProperty("Cookie", CookieVal);
        }
        if (!connection.getDoOutput()) {
            connection.setDoOutput(true);
        }
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type", "application/json");
        DataOutputStream out = new DataOutputStream(
                connection.getOutputStream());

        UUID uuid = UUID.randomUUID();
        int hashCode = uuid.toString().hashCode();

        JSONObject jObj = new JSONObject();

        jObj.put("format", 1);
        jObj.put("useragent", "ApiClient");
        jObj.put("rid", hashCode);
        jObj.put("parameters", chinaToUnicode(paras.toString()));
        jObj.put("timestamp", new Date().toString());
        jObj.put("v", "1.0");

        out.writeBytes(jObj.toString());
        out.flush();
        out.close();

        return connection;
    }

    // Login
    public static boolean login(String dbId, String user, String pwd, int lang)
            throws Exception {

        boolean bResult = false;

        String sUrl = "Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc";

        JSONArray jParas = new JSONArray();

        jParas.add(dbId);
        jParas.add(user);
        jParas.add(pwd);
        jParas.add(lang);

        HttpURLConnection connection = initUrlConn(sUrl, jParas);

        // 获取Cookie
        String key;
        for (int i = 1; (key = connection.getHeaderFieldKey(i)) != null; i++) {
            if ("Set-Cookie".equalsIgnoreCase(key)) {
                String tempCookieVal = connection.getHeaderField(i);
                if (tempCookieVal.startsWith("kdservice-sessionid")) {
                    CookieVal = tempCookieVal;
                    break;
                }
            }
        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            String sResult = new String(line.getBytes(), "utf-8");
            System.out.println(line);
            bResult = line.contains("\"LoginResultType\":1");
        }
        reader.close();

        connection.disconnect();

        return bResult;
    }

    // Save
    public static String save(String formId, String content) throws Exception {
        return invoke("Save", formId, content);
    }

    // batchSave
    public static String batchSave(String formId, String content) throws Exception {
        return invoke("BatchSave", formId, content);
    }

    // View
    public static String view(String formId, String content) throws Exception {
        return invoke("View", formId, content);
    }

    // Submit
    public static String submit(String formId, String content) throws Exception {
    	return invoke("Submit", formId, content);
    }

    // Audit
    public static String audit(String formId, String content) throws Exception {
    	return invoke("Audit", formId, content);
    }

    // UnAudit
    public static String unAudit(String formId, String content) throws Exception {
        return invoke("UnAudit", formId, content);
    }

    // StatusConvert
    public static void statusConvert(String formId, String content)
            throws Exception {
        invoke("StatusConvert", formId, content);
    }

    // draft
    public static void draft(String formId, String content)
            throws Exception {
        invoke("Draft", formId, content);
    }
    
    
    // draft
    public static void delete(String formId, String content)
            throws Exception {
        invoke("Delete", formId, content);
    }

    // allocate
    public static String allocate(String formId, String content)
            throws Exception {
        return invoke("Allocate", formId, content);
    }

    // executeBillQuery
    public static String executeBillQuery(String content) throws Exception {
        return query("ExecuteBillQuery", content);
    }

    // Push
    public static String push(String formId, String content) throws Exception {
        return invoke("Push",formId, content);
    }

    private static String invoke(String deal, String formId, String content)
            throws Exception {

        String sUrl = map.get(deal);
        JSONArray jParas = new JSONArray();
        jParas.add(formId);
        jParas.add(content);

        HttpURLConnection connectionInvoke = initUrlConn(sUrl, jParas);

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connectionInvoke.getInputStream()));

        String line;
        String sResult = null;
        while ((line = reader.readLine()) != null) {
            sResult = new String(line.getBytes(), "utf-8");
            System.out.println(sResult);
        }
        reader.close();

        connectionInvoke.disconnect();
        return sResult;
    }

    private static String query(String deal, String content) throws Exception {
        String sUrl = map.get(deal);
        JSONArray jParas = new JSONArray();
        jParas.add(content);

        HttpURLConnection connectionInvoke = initUrlConn(sUrl, jParas);

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connectionInvoke.getInputStream()));

        String line;
        String sResult = null;
        while ((line = reader.readLine()) != null) {
            sResult = new String(line.getBytes(), "utf-8");
            System.out.println(sResult);
        }
        reader.close();

        connectionInvoke.disconnect();
        return sResult;
    }

    /**
     * 把中文转成Unicode码
     *
     * @param str String
     * @return String
     */
    public static String chinaToUnicode(String str) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            int chr1 = str.charAt(i);
            // 汉字范围 \u4e00-\u9fa5 (中文)
            if (chr1 >= 19968) {
                result.append("\\u").append(Integer.toHexString(chr1));
            } else {
                result.append(str.charAt(i));
            }
        }
        return result.toString();
    }
}
